package com.szlanyou.thirdsdk.retrofit.util;

import android.text.TextUtils;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;

/**
 * @author 陈章
 * create at 2020/12/23 10:28
 * desc:RequestBody处理
 */
public class RequestBodyUtil {
    public static RequestBody createRequestBodyFromMap(Map paramsMap) {
        //OkHttp >= 4.x
        return RequestBody.create(GsonUtil.gson.toJson(paramsMap), MediaType.parse("application/json; charset=utf-8"));
        //OkHttp < 4.x
//        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"),GsonUtil.gson.toJson(paramsMap));
    }

    public static Map getMapFromRequestBody(RequestBody body){
        String jsonFromRequestBody = getJsonFromRequestBody(body);
        if(TextUtils.isEmpty(jsonFromRequestBody)){
            return new HashMap();
        }else{
            return GsonUtil.fromJson(jsonFromRequestBody);
        }
    }


    /**
     * 此方法不能用于解析文件，否则会造成oom。
     * @param body
     * @return
     */
    public static String  getJsonFromRequestBody(RequestBody body){
        if(body == null) {
            return null;
        }
        Buffer buffer = new Buffer();
        try {
            body.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = body.contentType();
            if (contentType != null) {
                //OkHttp 4.x以下没有Charsets类
//                charset = contentType.charset(Charsets.UTF_8);
                charset = contentType.charset(StandardCharsets.UTF_8);
            }
            String params = buffer.readString(charset);
            return params;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



}
